<?php

namespace Modules\Queue\Models;

use Phalcon\Di;
use Core\Mvc\Collection;
use Modules\Core\Models\Log;

class Queue extends Collection
{
    /**
     * @var int
     * 任务类型，0为一次性任务，大于0为周期性任务，以分钟为单位周期循环处
     */
    public $type;
    public $data;//传递给任务处理器的数据
    public $created;//任务创建时间
    public $changed;//任务最近更改时间
    public $log;//任务处理日志
    public $queueId;//上次执行队列的任务ID
    public $percentage = 0;
    public $notice = '';
    public $isRun = false;
    /**
     * @var int
     * 任务状态，0为正常，1为错误
     */
    public $state;
    /**
     * @var string
     * 所属的任务处理器
     */
    public $task;//所属任务

    public function run()
    {
        $di = Di::getDefault();
        $taskList = $di->getShared('config')->cache('task');
        //任务类型不存在
        if (!isset($taskList[$this->task])) {
            $this->error('任务处理器：' . $this->task . '不存在');
            return false;
        }

        //任务处理器不是合法调用结构
        if (!isCallable($taskList[$this->task]['callable'])) {
            $this->error('任务处理器调用方法：' . $taskList[$this->task]['callable'] . '不存在');
            return false;
        }

        //还未到执行时间的周期任务
        if ($this->type > 0 && time() < $this->changed + ($this->type * 60)) {
            return false;
        }

        //echo $taskList[$this->task]['callable'];
        $runState = call_user_func($taskList[$this->task]['callable'], $this);


        if ($runState === true) {
            $this->success();
            return true;
        } elseif (is_string($runState)) {
            $this->error($runState);
            return false;
        } elseif (is_array($runState)) {
            $this->data = $runState;
            $this->save();
        }

        return true;
    }

    public function isRun($run = true)
    {
        $this->isRun = $run;
        $this->save();
    }

    public function percentage($current, $total, $notice = '')
    {
        $base = 100 / $total;
        $output = ($current * $base) / ($total * $base);
        $this->percentage = floatval($output);
        $this->notice = $notice;
        $this->save();
    }

    public function success()
    {
        if ($this->type == 0) {
            $this->delete();
        } else {
            $this->changed = time();
            if (!is_array($this->log)) {
                $this->log = [];
            }
            $this->log[time()] = '成功运行';
            $this->save();
        }
        return true;
    }

    public function error($error)
    {
        Log::add([
            'data' => $error,
            'type' => 'queueModel',
            'level' => 'warning'
        ]);
        $this->state = 1;
        if (!is_array($this->log)) {
            $this->log = [];
        }
        $this->log[time()] = $error;
        $this->save();
    }
}
